# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql


class ScrapydemoPipeline:
    def open_spider(self, spider):
        self.conn = pymysql.connect(user='root', passwd='123456', host='master', port=3306, db='spiders')

        # 对由Spider发送过来的item进行处理

    def process_item(self, item, spider):
        # 写入MySQL

        title = item['title']
        year = item['year']
        country = item['country']
        category = item['category']
        comment = item['comment']
        score = item['score']
        comment_cnt = item['comment_cnt']
        try:
            with self.conn.cursor() as cursor:
                cursor.execute('insert into movies values(%s,%s,%s,%s,%s,%s,%s)',
                               (title, year, country, category, score, comment_cnt, comment))
        except Exception as e:
            print(e)
            # 发生了异常就进行回滚
            self.conn.rollback()
        else:
            # 没有发生异常就提交写入的数据
            self.conn.commit()

        return item

    def close_spider(self, spider):
        self.conn.close()
